package cn.zzm.transaction;

import cn.zzm.common.Constants;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @program: study
 * @description:事务
 * @author: 周昭名
 * @create: 2019-04-07 22:11
 **/
public class JmsTranAsyncComsumer {

    public static void main(String[] args) {
        /*连接工厂*/
        ConnectionFactory connectionFactory;
        /*连接*/
        Connection connection = null;
        /*会话*/
        final Session session;
        /*目的地*/
        Destination destination;
        /*消费者*/
        MessageConsumer messageConsumer;
        /*监听*/
        MessageListener messageListener;

        /*实例化连接工厂*/
        connectionFactory = new ActiveMQConnectionFactory(Constants.USERNAME, Constants.PASSWORD, Constants.BROKEURL);
        try {
            /*通过工厂获取连接*/
            connection = connectionFactory.createConnection();
            connection.start();
            /* 创建session
             * 第一个参数表示是否使用事务，第二次参数表示是否自动确认*/
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            /*创建一个queue*/
            destination = session.createQueue("transactionQueue");
            /*创建消息发送者*/
            messageConsumer = session.createConsumer(destination);

            messageListener = session.getMessageListener();
            messageConsumer.setMessageListener(new MessageListener() {
                public void onMessage(Message message) {
                    try {
                        System.out.println(((TextMessage)message).getText());
                        session.commit();
                    } catch (JMSException e) {
                        try {
                            session.rollback();
                        } catch (JMSException e1) {
                            e1.printStackTrace();
                        }
                        e.printStackTrace();
                    }
                }
            });

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

